<?php

namespace App\Http\Controllers\UI;

use App\Http\Controllers\Controller;
use App\Miya\Models\Area;
use App\Miya\Models\Info;
use App\Miya\Models\Module;
use Diglactic\Breadcrumbs\Breadcrumbs;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class ModuleController extends CommonController
{
    protected $data;

    public function pc(Module $module)
    {
        return view($module->module_tql, $this->buildData($module));
    }

    public function area(Area $area, Module $module)
    {
        $data = $this->buildData($module);
        $data['area'] = $area;
        $data['title'] = sprintf('%s_%s分站', $data['title'], $area->name);
        $data['keywords'] = miya('keyword')->derivatives($area, $module->keyword)->join(',');

        return view($module->module_tql, $data);
    }

    public function mobile(Module $module)
    {
        return view($module->wap_module_tql, $this->buildData($module));
    }

    protected function buildData(Module $module)
    {
        $data = [];
        $data['area'] = new Area();//地区兜底
        $module = Module::with(['classifies', 'infos' => function ($query) use ($module) {
            $query->whereHas('classify')->where('status', 1)
                ->where(function ($query) {
                    $query->where('is_delayed', 2)->orWhere(function ($query) {
                        $query->where('is_delayed', 1)->where('delayed_at', '<=', now());
                    });
                });
            $query = Info::rankByType($query, $module->info_rank_type);
        }, 'infos.keyword', 'infos.info_types.module_type', 'infos.classify.module:id,tag,name',
            'infos.module:id,name,tag', 'infos.classify:id,name,tag,module_id', 'keyword'])
            ->find($module->id);
        $module->classifies = $module->classifies->toTree();
        $module->infos = $module->infos->map(function ($info) {
            $info->avatar && $info->avatar = asset('uploads/' . $info->avatar);
            $info->images = array_map(function ($img) {
                return asset('uploads/' . $img);
            }, $info->images);
            $info->keywords = $info->getKeywords();
            return $info;
        });
        $data['module'] = $module;
        $data['title'] = $module->title ?? sprintf('%s_%s', $module->name, config('web.name'));
        $data['keywords'] = $module->keyword->keyword ?? '';
        $data['description'] = $module->description ?? config('web.description');
        $data['breadcrumb'] = Breadcrumbs::render('module', ['module' => $module]);

        return $data;
    }
}
